using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

namespace AdvancedInspector
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class ReadOnlyAttribute : Attribute, IListAttribute, IRuntimeAttribute, IRuntimeAttribute<bool>
	{
		public delegate bool ReadOnlyDelegate();

		private string methodName = string.Empty;

		private List<Delegate> delegates = new List<Delegate>();

		public string MethodName
		{
			get
			{
				return methodName;
			}
		}

		public Type Template
		{
			get
			{
				return typeof(ReadOnlyDelegate);
			}
		}

		public List<Delegate> Delegates
		{
			get
			{
				return delegates;
			}
			set
			{
				delegates = value;
			}
		}

		public ReadOnlyAttribute()
		{
		}

		public ReadOnlyAttribute(Delegate method)
		{
			delegates.Add(method);
		}

		public ReadOnlyAttribute(string methodName)
		{
			this.methodName = methodName;
		}

		public bool Invoke(int index)
		{
			if (delegates.Count == 0 || index >= delegates.Count)
			{
				return true;
			}
			try
			{
				return (bool)delegates[index].DynamicInvoke();
			}
			catch (Exception innerException)
			{
				if (innerException is TargetInvocationException)
				{
					innerException = ((TargetInvocationException)innerException).InnerException;
				}
				Debug.LogError(string.Format("Invoking a method to retrieve a ReadOnly attribute failed. The exception was \"{0}\".", innerException.Message));
				return false;
			}
		}
	}
}
